package com.example.jones.listener;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import com.example.jones.function.AlarmService;

import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TimePicker;
import android.widget.Toast;

public class AlarmOnClickListener implements OnClickListener {

    @Override
    public void onClick(final View v) {
        final Calendar c = Calendar.getInstance();
        final Context context = v.getContext();
        Dialog dialog = new TimePickerDialog(v.getContext(),
                new TimePickerDialog.OnTimeSetListener() {

                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay,
                            int minute) {
                        c.set(Calendar.HOUR_OF_DAY, hourOfDay);
                        c.set(Calendar.MINUTE, minute);

                        if (c.getTimeInMillis() < System.currentTimeMillis()) {
                            c.add(Calendar.DAY_OF_YEAR, 1);
                        }
                        SimpleDateFormat sf = new SimpleDateFormat(
                                "MM-dd HH:mm");
                        String tips = sf.format(c.getTime());
                        Intent intent = new Intent(context, AlarmService.class);
                        intent.setAction("com.jones.action.setalarm");
                        PendingIntent sender = PendingIntent.getService(
                                context, 0, intent, 0);
                        AlarmManager manager = (AlarmManager) ((context)
                                .getSystemService(Context.ALARM_SERVICE));
                        manager.setRepeating(AlarmManager.RTC_WAKEUP,
                                c.getTimeInMillis(), 24L * 60 * 60 * 1000,
                                sender);
                        Toast.makeText(context,
                                "推送设置成功，我们将于" + tips + "将最新的内容发送给您",
                                Toast.LENGTH_LONG).show();
                    }
                }, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), true);
        dialog.setTitle("设置推送时间");
        dialog.show();
    }
}
